<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { RefreshRight } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import * as echarts from 'echarts'

// 状态变量
const loading = ref(false)
const totalBikes = ref(0)
const availableBikes = ref(0)
const inUseBikes = ref(0)
const maintenanceBikes = ref(0)
const damagedBikes = ref(0)

// 图表实例
let bikeTypeChart: echarts.ECharts | null = null
let bikeStatusChart: echarts.ECharts | null = null
let maintenanceStatusChart: echarts.ECharts | null = null
let usageRankChart: echarts.ECharts | null = null

// 自行车图层
let bikeLayer: FeatureLayer | null = null

// 初始化
onMounted(() => {
  initBikeLayer()
  initCharts()
  loadStatistics()

  // 添加窗口调整事件
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口调整事件
  window.removeEventListener('resize', handleResize)

  // 释放图表实例
  if (bikeTypeChart) {
    bikeTypeChart.dispose()
    bikeTypeChart = null
  }
  if (bikeStatusChart) {
    bikeStatusChart.dispose()
    bikeStatusChart = null
  }
  if (maintenanceStatusChart) {
    maintenanceStatusChart.dispose()
    maintenanceStatusChart = null
  }
  if (usageRankChart) {
    usageRankChart.dispose()
    usageRankChart = null
  }
})

// 初始化自行车图层
const initBikeLayer = () => {
  bikeLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/rDRhdC4brwj3FLD5/arcgis/rest/services/cycleFeaturelayer/FeatureServer/0',
    outFields: ['*'],
  })
}

// 初始化图表
const initCharts = () => {
  // 初始化单车类型统计图表
  bikeTypeChart = echarts.init(document.getElementById('bikeTypeChart'))

  // 初始化单车状态统计图表
  bikeStatusChart = echarts.init(document.getElementById('bikeStatusChart'))

  // 初始化维修状态统计图表
  maintenanceStatusChart = echarts.init(document.getElementById('maintenanceStatusChart'))

  // 初始化使用次数排行榜图表
  usageRankChart = echarts.init(document.getElementById('usageRankChart'))
}

// 加载统计数据
const loadStatistics = async () => {
  if (!bikeLayer) return

  loading.value = true
  try {
    // 查询所有单车
    const query = bikeLayer.createQuery()
    query.where = '1=1'
    query.outFields = ['*']

    const results = await bikeLayer.queryFeatures(query)
    const bikes = results.features.map(feature => feature.attributes)

    // 计算总数量
    totalBikes.value = bikes.length

    // 按状态统计
    availableBikes.value = bikes.filter(bike => bike.Status === '可用').length
    inUseBikes.value = bikes.filter(bike => bike.Status === '使用中').length
    maintenanceBikes.value = bikes.filter(bike => bike.Status === '维修中').length
    damagedBikes.value = bikes.filter(bike => bike.Status === '损坏').length

    // 按类型统计
    const bikeTypeData = countByField(bikes, 'BikeType')
    updateBikeTypeChart(bikeTypeData)

    // 按状态统计
    const bikeStatusData = [
      { name: '可用', value: availableBikes.value },
      { name: '使用中', value: inUseBikes.value },
      { name: '维修中', value: maintenanceBikes.value },
      { name: '损坏', value: damagedBikes.value }
    ]
    updateBikeStatusChart(bikeStatusData)

    // 按维修状态统计
    const maintenanceBikesData = bikes.filter(bike => bike.Status === '维修中')
    const maintenanceStatusData = countByField(maintenanceBikesData, 'MaintenanceStatus')
    updateMaintenanceStatusChart(maintenanceStatusData)

    // 使用次数排行
    const usageRankData = bikes
      .map(bike => ({
        id: bike.BikeId,
        type: bike.BikeType,
        count: parseInt(bike.TotalUsageCount || '0')
      }))
      .sort((a, b) => b.count - a.count)
      .slice(0, 10) // 取前10名

    updateUsageRankChart(usageRankData)
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

// 按字段统计数量
const countByField = (data: any[], field: string) => {
  const counts: Record<string, number> = {}

  data.forEach(item => {
    const value = item[field] || '未知'
    counts[value] = (counts[value] || 0) + 1
  })

  return Object.entries(counts).map(([name, value]) => ({ name, value }))
}

// 更新单车类型统计图表
const updateBikeTypeChart = (data: { name: string, value: number }[]) => {
  if (!bikeTypeChart) return

  const option = {
    title: {
      text: '单车类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '单车类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }

  bikeTypeChart.setOption(option)
}

// 更新单车状态统计图表
const updateBikeStatusChart = (data: { name: string, value: number }[]) => {
  if (!bikeStatusChart) return

  const option = {
    title: {
      text: '单车状态分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '单车状态',
        type: 'pie',
        radius: '50%',
        data: data.map(item => ({
          ...item,
          itemStyle: {
            color: item.name === '可用' ? '#67C23A' :
                   item.name === '使用中' ? '#409EFF' :
                   item.name === '维修中' ? '#E6A23C' :
                   item.name === '损坏' ? '#F56C6C' : '#909399'
          }
        }))
      }
    ]
  }

  bikeStatusChart.setOption(option)
}

// 更新维修状态统计图表
const updateMaintenanceStatusChart = (data: { name: string, value: number }[]) => {
  if (!maintenanceStatusChart) return

  const option = {
    title: {
      text: '维修状态分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '维修状态',
        type: 'pie',
        radius: '50%',
        data: data.map(item => ({
          ...item,
          itemStyle: {
            color: item.name === '等待维修' ? '#E6A23C' :
                   item.name === '维修中' ? '#409EFF' :
                   item.name === '维修完成' ? '#67C23A' : '#909399'
          }
        }))
      }
    ]
  }

  maintenanceStatusChart.setOption(option)
}

// 更新使用次数排行榜图表
const updateUsageRankChart = (data: { id: string, type: string, count: number }[]) => {
  if (!usageRankChart) return

  const option = {
    title: {
      text: '单车使用次数排行榜',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['使用次数'],
      top: 'bottom'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: data.map(item => `${item.id} (${item.type})`),
      inverse: true
    },
    series: [
      {
        name: '使用次数',
        type: 'bar',
        data: data.map(item => item.count),
        itemStyle: {
          color: function(params: any) {
            // 根据排名设置不同的颜色
            const colorList = ['#E01F54', '#F5A31A', '#56A3F1', '#9FE080', '#917FD7', '#FF9A7A', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
            return colorList[params.dataIndex % colorList.length];
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}'
        }
      }
    ]
  }

  usageRankChart.setOption(option)
}

// 处理窗口调整
const handleResize = () => {
  bikeTypeChart?.resize()
  bikeStatusChart?.resize()
  maintenanceStatusChart?.resize()
  usageRankChart?.resize()
}

// 刷新数据
const refreshData = () => {
  loadStatistics()
}
</script>

<template>
  <div class="admin-statistics">
    <el-card class="statistics-card">
      <template #header>
        <div class="card-header">
          <h2>数据统计</h2>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData" :loading="loading" :icon="RefreshRight">
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 数据概览 -->
      <div class="statistics-overview">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-card shadow="hover" class="overview-card total-card">
              <div class="overview-item">
                <div class="overview-title">总单车数</div>
                <div class="overview-value">{{ totalBikes }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="5">
            <el-card shadow="hover" class="overview-card available-card">
              <div class="overview-item">
                <div class="overview-title">可用单车</div>
                <div class="overview-value">{{ availableBikes }}</div>
                <div class="overview-percent" v-if="totalBikes > 0">
                  {{ Math.round((availableBikes / totalBikes) * 100) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="5">
            <el-card shadow="hover" class="overview-card inuse-card">
              <div class="overview-item">
                <div class="overview-title">使用中单车</div>
                <div class="overview-value">{{ inUseBikes }}</div>
                <div class="overview-percent" v-if="totalBikes > 0">
                  {{ Math.round((inUseBikes / totalBikes) * 100) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="5">
            <el-card shadow="hover" class="overview-card maintenance-card">
              <div class="overview-item">
                <div class="overview-title">维修中单车</div>
                <div class="overview-value">{{ maintenanceBikes }}</div>
                <div class="overview-percent" v-if="totalBikes > 0">
                  {{ Math.round((maintenanceBikes / totalBikes) * 100) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="5">
            <el-card shadow="hover" class="overview-card damaged-card">
              <div class="overview-item">
                <div class="overview-title">损坏单车</div>
                <div class="overview-value">{{ damagedBikes }}</div>
                <div class="overview-percent" v-if="totalBikes > 0">
                  {{ Math.round((damagedBikes / totalBikes) * 100) }}%
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-wrapper">
              <div id="bikeTypeChart" class="chart"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-wrapper">
              <div id="bikeStatusChart" class="chart"></div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="mt-20">
          <el-col :span="12">
            <div class="chart-wrapper">
              <div id="maintenanceStatusChart" class="chart"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-wrapper">
              <div id="usageRankChart" class="chart"></div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div v-if="loading" class="loading-mask">
        <el-icon class="loading-icon" size="40"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" data-v-029747aa=""><path fill="currentColor" d="M512 64a32 32 0 0 1 32 32v192a32 32 0 0 1-64 0V96a32 32 0 0 1 32-32zm0 640a32 32 0 0 1 32 32v192a32 32 0 1 1-64 0V736a32 32 0 0 1 32-32zm448-192a32 32 0 0 1-32 32H736a32 32 0 1 1 0-64h192a32 32 0 0 1 32 32zm-640 0a32 32 0 0 1-32 32H96a32 32 0 0 1 0-64h192a32 32 0 0 1 32 32zM195.2 195.2a32 32 0 0 1 45.248 0L376.32 331.008a32 32 0 0 1-45.248 45.248L195.2 240.448a32 32 0 0 1 0-45.248zm452.544 452.544a32 32 0 0 1 45.248 0L828.8 783.552a32 32 0 0 1-45.248 45.248L647.744 692.992a32 32 0 0 1 0-45.248zM828.8 195.264a32 32 0 0 1 0 45.184L692.992 376.32a32 32 0 0 1-45.248-45.248l135.808-135.808a32 32 0 0 1 45.248 0zm-452.544 452.48a32 32 0 0 1 0 45.248L240.448 828.8a32 32 0 0 1-45.248-45.248l135.808-135.808a32 32 0 0 1 45.248 0z"></path></svg></el-icon>
        <div class="loading-text">正在加载数据...</div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.admin-statistics {
  padding: 20px;
}

.statistics-card {
  position: relative;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.statistics-overview {
  margin-bottom: 30px;
}

.overview-card {
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.overview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 10px;
}

.overview-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.overview-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.overview-percent {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.total-card .overview-value {
  color: #409EFF;
}

.available-card .overview-value {
  color: #67C23A;
}

.inuse-card .overview-value {
  color: #409EFF;
}

.maintenance-card .overview-value {
  color: #E6A23C;
}

.damaged-card .overview-value {
  color: #F56C6C;
}

.charts-container {
  margin-top: 20px;
}

.chart-wrapper {
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart {
  height: 350px;
  width: 100%;
}

.mt-20 {
  margin-top: 20px;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 100;
  border-radius: 8px;
}

.loading-icon {
  animation: rotating 2s linear infinite;
  color: #409EFF;
}

.loading-text {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
